<template>
    <div>
      <div class="attr-item" v-for="(items, indexs) in attriubteDefines" :key="indexs">
        <select class="variation-trait" @change="change(indexs)" :data-type="items.name" :data-idx="indexs">
          <option value="">Select {{items.name}}</option>
          <option v-for="(item, index) in items.options" :key="index" :data-title="item" :value="item">{{item}}</option>
        </select>
      </div>
    </div>
</template>

<script type="text/ecmascript-6">

  const spliter = '\u2299'
  export default {
    props: {
      attriubteDefines: {
        type: Array,
        default: function() {
          return []
        }
      },
      variations: {
        type: Array,
        default: function() {
          return []
        }
      },
      defaultVariation: {
        type: Object,
        default: function() {
          return {}
        }
      }
    },
    data() {
      return {
        // attriubteDefines: [
        //   {
        //     "name": "Size",
        //     "position": 0,
        //     "options": [
        //       "X-Large",
        //       "Large",
        //       "Small",
        //       "Medium"
        //     ]
        //   },
        //   {
        //     "name": "Color",
        //     "position": 1,
        //     "options": [
        //       "Stripe-2",
        //       "Tie Dye"
        //     ]
        //   }
        // ],
        // variations: [
        //   {
        //     "sku": "B01D4OQ2UK",
        //     "originalPrice": 19.99,
        //     "price": 10.00,
        //     "discountRate": 0.50,
        //     "currency": "USD",
        //     "description": "<ul class=\\\"a-unordered-lista-verticala-spacing-none\\\">\n              <li>\n               <span class=\\\"a-list-item\\\">\n                100% Polyester\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Pull On closure\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Our size is Asia size,not US/UK size. Asian S=US 0;Asian M=US 2/4;Asian L=US 6/8;Asian XL=US 10\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Material: 90%Polyester+10%Spandex, Stretchable fabric\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                High waist printed maxi skirt features a stretchy and foldable waistband\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Various styles in different patterns\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Wear For Club, Party, Lounging, Movie Nights, Shopping, Dancing, Working Out, And More!\n               </span>\n              </li>\n             </ul>\n             ",
        //     "images": [
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-MAIN.jpg",
        //         "position": 0
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT01.jpg",
        //         "position": 1
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT02.jpg",
        //         "position": 2
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT03.jpg",
        //         "position": 3
        //       }
        //     ],
        //     "url": "https://www.amazon.com/dp/B01D4OQ2UK",
        //     "productAttributes": [
        //       {
        //         "name": "Size",
        //         "value": "X-Large"
        //       },
        //       {
        //         "name": "Color",
        //         "value": "Stripe-2"
        //       }
        //     ]
        //   },
        //   {
        //     "sku": "B01D4OQ746",
        //     "originalPrice": 14.99,
        //     "price": 7.50,
        //     "discountRate": 0.50,
        //     "currency": "USD",
        //     "description": "<ul class=\\\"a-unordered-lista-verticala-spacing-none\\\">\n              <li>\n               <span class=\\\"a-list-item\\\">\n                100% Polyester\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Pull On closure\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Our size is Asia size,not US/UK size. Asian S=US 0;Asian M=US 2/4;Asian L=US 6/8;Asian XL=US 10\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Material: 90%Polyester+10%Spandex, Stretchable fabric\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                High waist printed maxi skirt features a stretchy and foldable waistband\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Various styles in different patterns\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Wear For Club, Party, Lounging, Movie Nights, Shopping, Dancing, Working Out, And More!\n               </span>\n              </li>\n             </ul>\n             ",
        //     "images": [
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-MAIN.jpg",
        //         "position": 0
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT01.jpg",
        //         "position": 1
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT02.jpg",
        //         "position": 2
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT03.jpg",
        //         "position": 3
        //       }
        //     ],
        //     "url": "https://www.amazon.com/dp/B01D4OQ746",
        //     "productAttributes": [
        //       {
        //         "name": "Size",
        //         "value": "Large"
        //       },
        //       {
        //         "name": "Color",
        //         "value": "Tie Dye"
        //       }
        //     ]
        //   },
        //   {
        //     "sku": "B01JOU4B60",
        //     "originalPrice": 19.99,
        //     "price": 10.00,
        //     "discountRate": 0.50,
        //     "currency": "USD",
        //     "description": "<ul class=\\\"a-unordered-lista-verticala-spacing-none\\\">\n              <li>\n               <span class=\\\"a-list-item\\\">\n                100% Polyester\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Pull On closure\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Our size is Asia size,not US/UK size. Asian S=US 0;Asian M=US 2/4;Asian L=US 6/8;Asian XL=US 10\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Material: 90%Polyester+10%Spandex, Stretchable fabric\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                High waist printed maxi skirt features a stretchy and foldable waistband\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Various styles in different patterns\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Wear For Club, Party, Lounging, Movie Nights, Shopping, Dancing, Working Out, And More!\n               </span>\n              </li>\n             </ul>\n             ",
        //     "images": [
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-MAIN.jpg",
        //         "position": 0
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT01.jpg",
        //         "position": 1
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT02.jpg",
        //         "position": 2
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT03.jpg",
        //         "position": 3
        //       }
        //     ],
        //     "url": "https://www.amazon.com/dp/B01JOU4B60",
        //     "productAttributes": [
        //       {
        //         "name": "Size",
        //         "value": "Small"
        //       },
        //       {
        //         "name": "Color",
        //         "value": "Tie Dye"
        //       }
        //     ]
        //   },
        //   {
        //     "sku": "B01D4OQ4ZS",
        //     "originalPrice": 14.99,
        //     "price": 7.50,
        //     "discountRate": 0.50,
        //     "currency": "USD",
        //     "description": "<ul class=\\\"a-unordered-lista-verticala-spacing-none\\\">\n              <li>\n               <span class=\\\"a-list-item\\\">\n                100% Polyester\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Pull On closure\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Our size is Asia size,not US/UK size. Asian S=US 0;Asian M=US 2/4;Asian L=US 6/8;Asian XL=US 10\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Material: 90%Polyester+10%Spandex, Stretchable fabric\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                High waist printed maxi skirt features a stretchy and foldable waistband\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Various styles in different patterns\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Wear For Club, Party, Lounging, Movie Nights, Shopping, Dancing, Working Out, And More!\n               </span>\n              </li>\n             </ul>\n             ",
        //     "images": [
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-MAIN.jpg",
        //         "position": 0
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT01.jpg",
        //         "position": 1
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT02.jpg",
        //         "position": 2
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT03.jpg",
        //         "position": 3
        //       }
        //     ],
        //     "url": "https://www.amazon.com/dp/B01D4OQ4ZS",
        //     "productAttributes": [
        //       {
        //         "name": "Size",
        //         "value": "Medium"
        //       },
        //       {
        //         "name": "Color",
        //         "value": "Tie Dye"
        //       }
        //     ]
        //   },
        //   {
        //     "sku": "B01D4OQ9DK",
        //     "originalPrice": 14.99,
        //     "price": 7.50,
        //     "discountRate": 0.50,
        //     "currency": "USD",
        //     "description": "<ul class=\\\"a-unordered-lista-verticala-spacing-none\\\">\n              <li>\n               <span class=\\\"a-list-item\\\">\n                100% Polyester\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Pull On closure\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Our size is Asia size,not US/UK size. Asian S=US 0;Asian M=US 2/4;Asian L=US 6/8;Asian XL=US 10\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Material: 90%Polyester+10%Spandex, Stretchable fabric\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                High waist printed maxi skirt features a stretchy and foldable waistband\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Various styles in different patterns\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Wear For Club, Party, Lounging, Movie Nights, Shopping, Dancing, Working Out, And More!\n               </span>\n              </li>\n             </ul>\n             ",
        //     "images": [
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-MAIN.jpg",
        //         "position": 0
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT01.jpg",
        //         "position": 1
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT02.jpg",
        //         "position": 2
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT03.jpg",
        //         "position": 3
        //       }
        //     ],
        //     "url": "https://www.amazon.com/dp/B01D4OQ9DK",
        //     "productAttributes": [
        //       {
        //         "name": "Size",
        //         "value": "X-Large"
        //       },
        //       {
        //         "name": "Color",
        //         "value": "Tie Dye"
        //       }
        //     ]
        //   },
        //   {
        //     "sku": "B01JOU49WG",
        //     "originalPrice": 19.99,
        //     "price": 10.00,
        //     "discountRate": 0.50,
        //     "currency": "USD",
        //     "description": "<ul class=\\\"a-unordered-lista-verticala-spacing-none\\\">\n              <li>\n               <span class=\\\"a-list-item\\\">\n                100% Polyester\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Pull On closure\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Our size is Asia size,not US/UK size. Asian S=US 0;Asian M=US 2/4;Asian L=US 6/8;Asian XL=US 10\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Material: 90%Polyester+10%Spandex, Stretchable fabric\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                High waist printed maxi skirt features a stretchy and foldable waistband\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Various styles in different patterns\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Wear For Club, Party, Lounging, Movie Nights, Shopping, Dancing, Working Out, And More!\n               </span>\n              </li>\n             </ul>\n             ",
        //     "images": [
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-MAIN.jpg",
        //         "position": 0
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT01.jpg",
        //         "position": 1
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT02.jpg",
        //         "position": 2
        //       },
        //       {
        //         "src": "/images/amazon/product/B01D4PKKCU-PT03.jpg",
        //         "position": 3
        //       }
        //     ],
        //     "url": "https://www.amazon.com/dp/B01JOU49WG",
        //     "productAttributes": [
        //       {
        //         "name": "Size",
        //         "value": "Small"
        //       },
        //       {
        //         "name": "Color",
        //         "value": "Stripe-2"
        //       }
        //     ]
        //   }
        // ],
        // defaultVariation: {
        //   "sku": "B01D4OQ2UK",
        //   "originalPrice": 19.99,
        //   "price": 10.00,
        //   "discountRate": 0.50,
        //   "currency": "USD",
        //   "description": "<ul class=\\\"a-unordered-lista-verticala-spacing-none\\\">\n              <li>\n               <span class=\\\"a-list-item\\\">\n                100% Polyester\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Pull On closure\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Our size is Asia size,not US/UK size. Asian S=US 0;Asian M=US 2/4;Asian L=US 6/8;Asian XL=US 10\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Material: 90%Polyester+10%Spandex, Stretchable fabric\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                High waist printed maxi skirt features a stretchy and foldable waistband\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Various styles in different patterns\n               </span>\n              </li>\n              <li>\n               <span class=\\\"a-list-item\\\">\n                Wear For Club, Party, Lounging, Movie Nights, Shopping, Dancing, Working Out, And More!\n               </span>\n              </li>\n             </ul>\n             ",
        //   "images": [
        //     {
        //       "src": "/images/amazon/product/B01D4PKKCU-MAIN.jpg",
        //       "position": 0
        //     },
        //     {
        //       "src": "/images/amazon/product/B01D4PKKCU-PT01.jpg",
        //       "position": 1
        //     },
        //     {
        //       "src": "/images/amazon/product/B01D4PKKCU-PT02.jpg",
        //       "position": 2
        //     },
        //     {
        //       "src": "/images/amazon/product/B01D4PKKCU-PT03.jpg",
        //       "position": 3
        //     }
        //   ],
        //   "url": "https://www.amazon.com/dp/B01D4OQ2UK",
        //   "productAttributes": [
        //     {
        //       "name": "Size",
        //       "value": "X-Large"
        //     },
        //     {
        //       "name": "Color",
        //       "value": "Stripe-2"
        //     }
        //   ]
        // },
        // 所有从产品中提取的属性几集合
        keys: [],
        // 所有库存的集合
        sku_list: [],
        // 所有路径 集合 幂集
        res: {},
        // 所有路径 属性 以及 sku 总集
        r: {},
        // 已选中的缓存
        selectedCache: []
      }
    },
    created() {
      const _this = this
      this.variations.forEach(function(item) {
        let ret = {}
        item.productAttributes.forEach(function(t) {
          ret[t.name] = t.value
        })
        ret.skuId = item.sku
        _this.sku_list.push(ret)
      })
      for (var attr_key in this.sku_list[0]) {
        if (!this.sku_list[0].hasOwnProperty(attr_key)) continue;
        if (attr_key !== 'skuId') this.keys.push(attr_key)
      }
      this.r = this._combineAttr(this.sku_list, this.keys)
      this._buildResult(this.r.items)
    },
    mounted() {
      this.$nextTick(() => {
        this._initSelect()
        this._updateStatus(this._getSelectedItem())
      })
    },
    methods: {
      change() {
        this._updateStatus(this._getSelectedItem())
        this._showResult()
      },
      _selectItem(index, indexs) {
        const sel = this.$refs.Size[indexs].getElementsByClassName('dropdown-content-value')

        this._bindEvent(sel[index])
        this._updateStatus(this._getSelectedItem())
      },
      /* 初始选中默认变体 */
      _initSelect() {
        const defaultProduct = this.defaultVariation
        defaultProduct.productAttributes.forEach(function(item, index) {
          $('select').filter('[data-type="'+ item.name +'"]').val(item.value)
        })
      },
      // 计算组合数据
      _combineAttr(data, keys) {
        var allKeys = []
        var result = {}

        for (var i = 0; i < data.length; i++) {
          var item = data[i]
          var values = []

          for (var j = 0; j < keys.length; j++) {
            var key = keys[j]
            if (!result[key]) result[key] = []
            if (result[key].indexOf(item[key]) < 0) result[key].push(item[key])
            values.push(item[key])
          }
          allKeys.push({
            path: values.join(spliter),
            sku: item['skuId']
          })
        }
        return {
          result: result,
          items: allKeys
        }
      },
      // 获取所有路径 数组
      _getAllKeys(arr) {
        var result = []
        for (var i = 0; i < arr.length; i++) { result.push(arr[i].path) }
        return result
      },
      /**
       * 取得集合的所有子集「幂集」
       * */
      _powerset(arr) {
        var ps = [[]];
        for (var i=0; i < arr.length; i++) {
          for (var j = 0, len = ps.length; j < len; j++) {
            ps.push(ps[j].concat(arr[i]));
          }
        }
        return ps;
      },
      /**
       * 生成所有子集是否可选、库存状态 map
       */
      _buildResult(items) {
        var allKeys = this._getAllKeys(items)
        for (var i = 0; i < allKeys.length; i++) {
          var curr = allKeys[i]
          var sku = items[i].sku
          var values = curr.split(spliter)

          // var allSets = getAllSets(values)
          var allSets = this._powerset(values)

          // 每个组合的子集
          for (var j = 0; j < allSets.length; j++) {
            var set = allSets[j]
            var key = set.join(spliter)

            if (this.res[key]) {
              this.res[key].skus.push(sku)
            } else {
              this.res[key] = {
                skus: [sku]
              }
            }
          }
        }
      },
      _trimSpliter(str, spliter) {
        // ⊙abc⊙ => abc
        // ⊙a⊙⊙b⊙c⊙ => a⊙b⊙c
        var reLeft        = new RegExp('^' + spliter + '+', 'g');
        var reRight       = new RegExp(spliter + '+$', 'g');
        var reSpliter = new RegExp(spliter + '+', 'g');
        return str.replace(reLeft, '')
          .replace(reRight, '')
          .replace(reSpliter, spliter)
      },
      /**
       * 获取当前选中的属性
       */
      _getSelectedItem() {
        var result = []
        $.each($('.variation-trait'), function(index, item) {
          result.push($(item).val())
        })
        return result
      },
      /**
       * 更新所有属性状态
       */
      _updateStatus(selected) {
        for (var i = 0; i < this.keys.length; i++) {
          var key = this.keys[i];
          var data = this.r.result[key]
          var hasActive = !!selected[i]
          var copy = selected.slice()

          for (var j = 0; j < data.length; j++) {
            var item = data[j]
            if (selected[i] == item) continue
            copy[i] = item

            var curr = this._trimSpliter(copy.join(spliter), spliter)

            var $item = $('select').filter('[data-type="'+ key +'"]').find('[value="'+ item +'"]')

            if (this.res[curr]) {
              // $item.removeClass('disabled')
              $item.attr('disabled', false)
            } else {
              // $item.addClass('disabled')
              $item.attr('disabled', true)
            }
          }
        }
      },
      _showResult() {
        var result = this._getSelectedItem()
        var s = []
        for (var i = 0; i < result.length; i++) {
          var item = result[i];
          if (!!item) {
            s.push(item)
          }
        }
        // debugger
        if (s.length === this.keys.length) {
          var curr = this.res[s.join(spliter)]
          if (curr) {
            // s = s.concat(curr.skus)
            this._transSku(curr.skus[0])
          }

        }
      },
      /**
       * 向外界传递sku
       */
      _transSku(sku) {
        this.$emit('skuChanged', sku)
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">

  .disabled
    background: #ccc
  .variation-trait
    display: inline-block;
    width: 100%
    background-color: #fff
    border: 1px solid #a5a8ab
    border-radius: 2px;
    font-size: 17px;
    margin: 12px 0
    transition: background-color .25s ease-out,border-color .25s ease-out,color .25s ease-out;
    background: no-repeat 100%;
    background-image: url(../../../static/img/arrow-green.svg);
    background-size: 40px 20px
    padding: 8px 36px 8px 12px;
    appearance: none;
    outline none
</style>
